package lee.vioson.ebook.viewmodels

import kotlinx.coroutines.flow.StateFlow
import lee.vioson.composecommon.base.mvi.BaseViewModel
import lee.vioson.composecommon.base.mvi.Reducer
import lee.vioson.composecommon.base.mvi.UiEvent
import lee.vioson.composecommon.base.mvi.UiState

/**
 *Author:viosonlee
 *Date:2023/6/1
 *DESCRIPTION:
 */
class MainAppViewModel : BaseViewModel<MainAppViewModel.State, MainAppViewModel.Event>() {
    private val reducer = SubReducer(State())

    override val state: StateFlow<State>
        get() = reducer.state

    override fun sendEvent(event: Event) {
        reducer.sendEvent(event)
    }


    private class SubReducer(initialState: State) :
        Reducer<State, Event>(initialState) {
        override fun reduce(oldState: State, event: Event) {
            when (event) {
                is Event.OnLauncherDismiss -> setState(oldState.copy(showLauncher = false))
                is Event.OnExitApp -> setState(oldState.copy(showLauncher = true))
                is Event.OnRequestLogin -> setState(oldState.copy(reLogin = oldState.reLogin + 1))
                is Event.OnShowToast -> setState(
                    oldState.copy(
                        toast = event.toast,
                        toastCount = oldState.toastCount + 1
                    )
                )

                is Event.OnLoadingChange -> setState(
                    oldState.copy(
                        showLoading = event.showLoading,
                        loadMessage = event.loadMessage
                    )
                )
            }
        }
    }

    data class State(
        val showLauncher: Boolean = true,
        val showLoading: Boolean = false,
        val loadMessage: String? = null,
        val toast: String? = null,
        val toastCount: Int = 0,//for same content toast
        val reLogin: Int = 0,
    ) :
        UiState

    sealed class Event : UiEvent {
        object OnLauncherDismiss : Event()
        object OnExitApp : Event()
        data class OnShowToast(val toast: String?) : Event()
        object OnRequestLogin : Event()
        data class OnLoadingChange(val showLoading: Boolean, val loadMessage: String?) : Event()
    }
}